package com.centling.bluecollar.recruit.service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javafx.geometry.Orientation;

import javax.annotation.Resource;
import javax.management.RuntimeErrorException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.centling.bluecollar.base.page.PageBean;
import com.centling.bluecollar.base.page.Pagination;
import com.centling.bluecollar.customer.DAO.EnterpriseCustomerDAO;
import com.centling.bluecollar.customer.entity.EnterpriseCustomer;
import com.centling.bluecollar.customer.entity.OperatePost;
import com.centling.bluecollar.customer.entity.Organization;
import com.centling.bluecollar.privilege.entity.Account;
import com.centling.bluecollar.recruit.DAO.DayRecruitDAO;
import com.centling.bluecollar.recruit.entity.DayRecruit;
import com.centling.bluecollar.recruit.entity.Template_DayRecruit;
import com.centling.bluecollar.staff.entity.StaffInfo;
import com.centling.bluecollar.util.ExcelOperations;
import com.centling.bluecollar.util.StaticConstant;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;

@Service("dayRecruitService")
public class DayRecruitService {
	@Resource
	private DayRecruitDAO dayRecruitDAO;
	@Resource
	private EnterpriseCustomerDAO enterpriseCustomerDAO;
	
	public void update(DayRecruit dayRecruit){
		dayRecruitDAO.update(dayRecruit);
		
	}
	
	
	public void delete(String ids){
		
		dayRecruitDAO.delete(ids);
	}
	
	public void add(DayRecruit dayRecruit){
		dayRecruitDAO.add(dayRecruit);
		
	}


	public List<DayRecruit> findByID(String id) {
		// TODO Auto-generated method stub
		
		return dayRecruitDAO.findById(id);
		
	}
	
	/**获得list总数据 和 记录条数 
	 * @param organization 
	 * @return
	 */
	public Pagination find(PageBean page, DayRecruit instance,String date_start,String date_end, Account account) {
	
		Pagination pag = new Pagination();
		int total=0;
		//分页后数据
		List<DayRecruit> list = dayRecruitDAO.findByExample(page, instance,date_start,date_end,account);
		pag.setRows(list);
		// 总数据
		List<DayRecruit> list2=dayRecruitDAO.findByExample(null, instance,date_start,date_end,account);
		if(list2.size()>0)
			total=Integer.parseInt(list2.get(0).getWriter());
		pag.setTotal( total+ "");//避免为 null
		return pag;
	}


	public List findfenAll(Account account) {
		//总公司保险合同文员
		if(account.getPost().getId().equals(StaticConstant.HEADQUARTERS_INSURANCECLERK_ID)||account.getPost().getId().equals(StaticConstant.BRANCH_INSURANCECONTRACTCLERK_ID)){
			List <Organization> org=new ArrayList<Organization>();//结果
			List <EnterpriseCustomer>list=account.getEnterpriseCustomers();//企业源
			if(list!=null){
				Organization t=null;
				int flag;//标识重复
			for(int i=0;i<list.size();i++){
				 flag=0;
				t=list.get(i).getOrganization();
				for(int j=i+1;j<list.size();j++)
					if(t.getId().equals(list.get(j).getOrganization().getId())){
						
						flag=1;//重复
					}
				if(flag==0){
					org.add(t);
				}
				}
			}
			return org;
		}
		else
		 return dayRecruitDAO.findfenAll(account);
	}
	

	public List findqiyeAll(String org_id) {
		
		return dayRecruitDAO.findqiyeAll(org_id);
	}


	public List<DayRecruit> findByPagination(int currentPage, int pageSize,Map<String, Object> searchmap,Account account) {
		
		
		return dayRecruitDAO.findByExample(currentPage, pageSize,searchmap,account);
	}

	@Resource
	public SessionFactory sessionFactory;
	public int getTotal() {
		// TODO Auto-generated method stub
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
	    String hql = "from DayRecruit";  
	    Query query = session.createQuery(hql);  
	    List<DayRecruit> dayrecruit = query.list();  	
		session.getTransaction().commit();		
		return dayrecruit.size();
	}

//导出所选行的数据 很据id 查找结果
	public List<Object[]> exportByid(String ids) {
		
		List<Object[]> objList = new ArrayList<Object[]>();
		List<DayRecruit> dayrec_list=dayRecruitDAO.findById(ids);
		if(dayrec_list!=null&&dayrec_list.size()>0){
			for(int i=0;i<dayrec_list.size();i++){
				Object[] obj=new Object[7];
				DayRecruit rec=new DayRecruit();
				rec=dayrec_list.get(i);
				if(rec!=null){
					obj[0]=rec.getDate();
					obj[1]=rec.getCustomer().getOrganization().getOrganizationName();
					obj[2]=rec.getCustomer().getEnterpriseName();
					obj[3]=(rec.getViewerNu())==null?"":rec.getViewerNu();
					obj[4]=(rec.getEntryNu()==null)?"":rec.getEntryNu();
					if(rec.getViewerNu()!=null&&rec.getEntryNu()!=null)
						obj[5]=(Math.round(Double.parseDouble(rec.getEntryNu())/Double.parseDouble(rec.getViewerNu())*100))/1.0+"%";
					else
						obj[5]="";
					obj[6]=(rec.getRemarks()==null)?"":rec.getRemarks();
					objList.add(obj);
				}
			}
		}
		return objList;
	}


	/**
	 * @param rec
	 * @param account
	 * @return
	 */
	public List<Object[]> export(DayRecruit dayRec,Account account,Map<String, Object> searchmap) {
		List<Object[]> objList = new ArrayList<Object[]>();
		PageBean page=new PageBean();
		page.setPage(-1);
		page.setRows(-1);
		List<DayRecruit> dayrec_list=dayRecruitDAO.findByExample(-1, -1,searchmap,account);
		if(dayrec_list!=null&&dayrec_list.size()>0){
			for(int i=0;i<dayrec_list.size();i++){
				Object[] obj=new Object[7];
				DayRecruit rec=new DayRecruit();
				rec=dayrec_list.get(i);
				if(rec!=null){
					obj[0]=rec.getDate();
					obj[1]=rec.getCustomer().getOrganization().getOrganizationName();
					obj[2]=rec.getCustomer().getEnterpriseName();
					obj[3]=(rec.getViewerNu())==null?"":rec.getViewerNu();
					obj[4]=(rec.getEntryNu()==null)?"":rec.getEntryNu();
					if(rec.getViewerNu()!=null&&rec.getEntryNu()!=null)
						obj[5]=(Math.round(Double.parseDouble(rec.getEntryNu())/Double.parseDouble(rec.getViewerNu())*100))/1.0+"%";
					else
						obj[5]="";
					obj[6]=(rec.getRemarks()==null)?"":rec.getRemarks();
					objList.add(obj);
				}
			}
		}
		return objList;
	}


	public List<Object[]> export(DayRecruit dayRec, String date_start,String date_end,Account account) {
		List<Object[]> objList = new ArrayList<Object[]>();
		PageBean page=new PageBean();
		page.setPage(-1);
		page.setRows(-1);
		List<DayRecruit> dayrec_list=dayRecruitDAO.findByExample(page, dayRec,date_start,date_end, account);
		if(dayrec_list!=null&&dayrec_list.size()>0){
			for(int i=0;i<dayrec_list.size();i++){
				Object[] obj=new Object[7];
				DayRecruit rec=new DayRecruit();
				rec=dayrec_list.get(i);
				if(rec!=null){
					obj[0]=rec.getDate();
					obj[1]=rec.getCustomer().getOrganization().getOrganizationName();
					obj[2]=rec.getCustomer().getEnterpriseName();
					obj[3]=(rec.getViewerNu())==null?"":rec.getViewerNu();
					obj[4]=(rec.getEntryNu()==null)?"":rec.getEntryNu();
					if(rec.getViewerNu()!=null&&rec.getEntryNu()!=null)
						obj[5]=(Math.round(Double.parseDouble(rec.getEntryNu())/Double.parseDouble(rec.getViewerNu())*100))/1.0+"%";
					else
						obj[5]="";
					obj[6]=(rec.getRemarks()==null)?"":rec.getRemarks();
					objList.add(obj);
				}
			}
		}
		return objList;
	}

/**
 * 读取表格内容
 * @param absolutePath
 * @param i
 * @return
 * @throws Exception
 */
	public ArrayList<Object> readExcel(String absolutePath, int i)throws Exception {
		// TODO Auto-generated method stub
		
		ExcelOperations oper = new ExcelOperations();
		ArrayList<Object> list = oper.readExcel(absolutePath,
				Template_DayRecruit.class, columnHeaders,i );
		
		return list;
	}
	
	public static final String[] columnHeaders = { "date",
		"remarks", "viewerNu",
		"entryNu", "customerName"};
	/**
	 * 导入dataList中的日清信息
	 * 
	 * @param dataList
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public String importDayrecruit(List<Object> dataList, Account user)
			throws Exception {
	
		String failImport = "";
		if (dataList != null && dataList.size() > 0) {	
			
			//根据公司user找到对应公司 根据公司找到对应的 招聘企业 根据招聘企业 
			Organization org = dayRecruitDAO.findOrganizationById(user.getOrganization().getId());
			
			List<EnterpriseCustomer> customers = dayRecruitDAO.findAllEnterpriseCustomerByOrg(user.getOrganization().getId());
			
			
			
			for (int i = 0; i < dataList.size(); i++) {
				DayRecruit dayRec = new DayRecruit();
				Template_DayRecruit t_dayRecruit = new Template_DayRecruit();
				t_dayRecruit = (Template_DayRecruit) dataList.get(i);
				dayRec.setWriter(user.getLoginName());
				dayRec.setDatatime(new Date());
				dayRec.setRemarks(t_dayRecruit.getRemarks().trim());
				//dayRec.
				//验证招聘日期
				if(isValidDate(t_dayRecruit.getDate().trim()) && StringUtils.isNotBlank(t_dayRecruit.getDate().trim())){					  					
					 dayRec.setDate(t_dayRecruit.getDate().toString());
					
				}else throw new RuntimeException("第" + (i + 2)
						+ "行填写招聘日清日期有误，请重新确定");		
				//验证填写人
/*				if(StringUtils.isNotBlank(dayRec.getWriter()) && dayRec.getWriter().equals(user.getUserName())){
					dayRec.setWriter(dayRec.getWriter().trim());					
				}
				else{
					throw new RuntimeException("第" + (i + 2)
							+ "行填写输入人有误，请填写您的登录账号，请重新确定");
				}*/												
				//验证面试人数
				if(isNumeric(t_dayRecruit.getViewerNu().trim()) && StringUtils.isNotBlank(t_dayRecruit.getViewerNu().trim())){					
					dayRec.setViewerNu(t_dayRecruit.getViewerNu().trim());					
				}
				else throw new RuntimeException("第" + (i + 2)
						+ "行填写面试人数有误，请重新确定");
				//验证入职人数
				if(isNumeric(t_dayRecruit.getEntryNu().trim()) && StringUtils.isNotBlank(t_dayRecruit.getEntryNu().trim())){
					
				int  re = 	Double.valueOf(t_dayRecruit.getEntryNu().trim()).compareTo(Double.valueOf(t_dayRecruit.getViewerNu().trim()));
			      if(re <1){			    	  			      
					dayRec.setEntryNu(t_dayRecruit.getEntryNu().trim());	}
			      else {
			    	  throw new RuntimeException("第" + (i + 2)
								+ "行入职人数大于面试人数，请重新确定");
				}
				}
				else throw new RuntimeException("第" + (i + 2)
						+ "行填写入职人数有误，请重新确定");
				
				//验证招聘企业  从模板中获取招聘企业的名字 查询出 此公司所有的招聘企业 对应的话  取 招聘企业这个对象赋值给dayR

				// 验证所属公司
				if(StringUtils.isNoneBlank(t_dayRecruit.getCustomerName().trim())){
					boolean isOK = false;
					if(customers != null && customers.size()>0){
			    	for(int j =0;j<customers.size();j++){
					if(customers.get(j).getEnterpriseName().equals(t_dayRecruit.getCustomerName().trim())){
						
						dayRec.setCustomer(customers.get(j));
						isOK = true;
						break;//跳出当前循环
					}
					
				}
				
				}
					if (!isOK) {
						throw new RuntimeException("第" + (i + 2)
								+ "行招聘企业输入有误，请重新确定");
					}
				}
				
				dayRecruitDAO.add(dayRec);
			}
		} else {
			throw new RuntimeException("导入数据为空");
		}
		return failImport;
	}
	//验证字符串是否为数字
		public static boolean isNumeric(String str){  
			   for(int i=str.length();--i>=0;){  
			      int chr=str.charAt(i);  
			      if(chr<48 || chr>57)  
			         return false;  
			   }  
			   return true;  
			} 
		/**
		 * 判断时间格式 格式必须为“YYYY-MM-dd”
		 * @param str
		 * @return
		 */
	    public boolean isValidDate(String str) {  
	        //String str = "2007-01-02";  
	        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
	        try{  
	            Date date = (Date)formatter.parse(str);  
//	            DebugPrintf.Printf(str);  
//	            DebugPrintf.Printf(formatter.format(date));  
	            return str.equals(formatter.format(date));  
	        }catch(Exception e){  
	            return false;  
	        }  
	    } 	    	
}
